<template>
  <view class="container">
    <!-- 头部导航栏 -->
    <view class="header">
      <text class="header-title">添加服用药物</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 药物名称选择 -->
      <view class="form-item">
        <text class="label required">药物名称</text>
        <picker @change="bindPickerChange" :value="pickerIndex" :range="medicationOptions" v-if="medicationOptions.length > 0">
          <view class="picker-input">{{ pickerIndex === -1 ? "请选择药品名称" : medicationOptions[pickerIndex] }}</view>
        </picker>
        <view class="picker-input" v-else>加载药品列表中...</view>
      </view>

      <!-- 详细药物名称（选择“其他”时显示） -->
      <view class="form-item" v-if="medicationOptions[pickerIndex] === '其他'">
        <text class="label required">详细药物名称</text>
        <input class="input" type="text" v-model="formData.customMedicationName" placeholder="请输入详细药物名称" />
      </view>

      <!-- 常见用量用法 -->
      <view class="form-item" v-if="formData.medicationName !== ''">
        <text class="label required">常见用量用法</text>
        <input
          class="input"
          type="text"
          v-model="formData.commonUsage"
          :placeholder="getPlaceholder('commonUsage')"
          :disabled="isFixedDosage"
        />
      </view>

      <!-- 药物备注 -->
      <view class="form-item" v-if="formData.medicationName !== ''">
        <text class="label required">药物备注</text>
        <input
          class="input"
          type="text"
          v-model="formData.medicationNotes"
          :placeholder="getPlaceholder('medicationNotes')"
          :disabled="isFixedDosage"
        />
      </view>

      <!-- 自己的用量用法 -->
      <view class="form-item">
        <text class="label required">当前用量用法</text>
        <input class="input" type="text" v-model="formData.myUsage" placeholder="请输入您的当前用量用法" />
      </view>

      <!-- 自己的剩余药量 -->
      <view class="form-item">
        <text class="label required">剩余药量</text>
        <input class="input" type="number" v-model="formData.remainingDosage" placeholder="请输入您的剩余药量" />
      </view>

      <!-- 提交按钮 -->
      <button class="submit-button" @click="submitForm" :disabled="medicationOptions.length === 0">提交</button>
    </view>
  </view>
</template>

<script>
import config from '../../config.js';
export default {
  data() {
    return {
      medicationOptions: [], // 从接口获取的药品列表+其他
      pickerIndex: -1,
      formData: {
        medicationName: '',
        customMedicationName: '',
        commonUsage: '',
        medicationNotes: '',
        myUsage: '',
        remainingDosage: '',
      },
      fixedMedicationData: {}, // 从接口获取的固定药品信息
      drugList: [] // 存储接口返回的启用药品原始数据
    };
  },
  computed: {
    isFixedDosage() {
      const selectedMed = this.medicationOptions[this.pickerIndex];
      // 判断是否为接口返回的启用药品（非其他）
      return selectedMed !== '其他' && this.fixedMedicationData[selectedMed] !== undefined;
    },
  },
  onLoad() {
    // 页面加载时获取药品列表
    this.fetchAllDrugs();
  },
  methods: {
    // 从后端获取所有启用的药品
    fetchAllDrugs() {
      uni.request({
        url: `${config.baseUrl}/patient/getAllDrug`,
        method: 'GET',
        header: {
          'Authorization': uni.getStorageSync('token') || ''
        },
        success: (res) => {
          if (res.data && res.data.code === 1) {
            // 过滤出启用状态的药品（根据后端实际返回的isused值调整判断条件）
            const enabledDrugs = (res.data.data || []).filter(drug => 
              drug.isused === true || drug.isused === '启用' || drug.isused === 1
            );
            
            this.drugList = enabledDrugs;
            // 构建药品选择列表（添加"其他"选项）
            this.medicationOptions = enabledDrugs.map(drug => drug.name).concat(['其他']);
            // 构建固定药品信息映射（用于快速查询用法和备注）
            this.fixedMedicationData = enabledDrugs.reduce((map, drug) => {
              map[drug.name] = {
                commonUsage: drug.method || '',
                medicationNotes: drug.remark || ''
              };
              return map;
            }, {});
          } else {
            uni.showToast({
              title: '获取药品列表失败',
              icon: 'none'
            });
            // 失败时至少保留"其他"选项
            this.medicationOptions = ['其他'];
          }
        },
        fail: (err) => {
          console.error('获取药品列表失败:', err);
          uni.showToast({
            title: '网络错误，获取药品列表失败',
            icon: 'none'
          });
          // 网络错误时至少保留"其他"选项
          this.medicationOptions = ['其他'];
        }
      });
    },
    
    bindPickerChange(e) {
      this.pickerIndex = e.detail.value;
      this.formData.medicationName = this.medicationOptions[this.pickerIndex];

      // 根据选择的药物更新常见用量用法和药物备注
      if (this.isFixedDosage) {
        const selectedMed = this.medicationOptions[this.pickerIndex];
        this.formData.commonUsage = this.fixedMedicationData[selectedMed].commonUsage;
        this.formData.medicationNotes = this.fixedMedicationData[selectedMed].medicationNotes;
      } else {
        // 如果选择“其他”，清空并允许用户输入
        this.formData.commonUsage = '';
        this.formData.medicationNotes = '';
      }
      this.formData.customMedicationName = ''; // 切换时清空自定义药物名称
    },
    
    getPlaceholder(field) {
      if (this.isFixedDosage) {
        return this.fixedMedicationData[this.medicationOptions[this.pickerIndex]][field];
      }
      return field === 'commonUsage' ? '请输入常见用量用法' : '请输入药物备注';
    },
    
    checkForm() {
      // 检查必填项
      if (this.medicationOptions[this.pickerIndex] === '其他' && !this.formData.customMedicationName) {
        uni.showToast({
          title: '请填写详细药物名称',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.commonUsage) {
        uni.showToast({
          title: '请填写常见用量用法',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.medicationNotes) {
        uni.showToast({
          title: '请填写药物备注',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.myUsage) {
        uni.showToast({
          title: '请填写当前用量用法',
          icon: 'none',
        });
        return false;
      }
      if (!this.formData.remainingDosage) {
        uni.showToast({
          title: '请填写剩余药量',
          icon: 'none',
        });
        return false;
      }
      return true;
    },
    
    submitForm() {
      if(!this.checkForm()) {
        return;
      }
      
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      const medicationName = this.formData.medicationName === '其他' 
        ? this.formData.customMedicationName 
        : this.formData.medicationName;
      
      const formData = {
        hospitalNumber,
        medicationName,
        commonDosageUsage: this.formData.commonUsage,
        medicationNotes: this.formData.medicationNotes,
        currentDosageUsage: this.formData.myUsage,
        currentStockAmount: this.formData.remainingDosage
      };
      
      console.log(formData);
      
      uni.request({
        url: `${config.baseUrl}/puwai/addMedicineInfo`,
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') || ''
        },
        success: (res) => {
          if (res.data && res.data.code === 1) {
            uni.showToast({
              title: '成功添加服用药品',
              icon: 'success'
            });
            
            // 2秒后返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          } else {
            uni.showToast({
              title: res.data.msg || '添加失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('添加服用药品失败:', err);
          uni.showToast({
            title: '添加失败',
            icon: 'none'
          });
        }
      });
    },
  },
};
</script>

<style>
/* 样式部分保持不变 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  width: 100%;
  height: 90rpx;
  background-color: #007aff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.form-container {
  padding: 30rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.label {
  font-size: 30rpx;
  color: #333;
  padding-bottom: 10rpx;
  position: relative;
  align-self: flex-start;
  padding-left: 27rpx;
}

.required::before {
  content: '*';
  color: red;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  margin-right: 8rpx;
}

.input {
  flex: 1;
  font-size: 30rpx;
  padding: 15rpx 0;
  color: #666;
  margin-top: 20rpx;
  min-height: 70rpx;
  line-height: 70rpx;
  box-sizing: border-box;
  border: none;
  border-bottom: 1rpx solid #e0e0e0;
  background-color: #fff;
  padding-left: 15rpx;
}

.picker-input {
  display: flex;
  align-items: center;
  flex: 1;
  font-size: 30rpx;
  padding: 15rpx 0;
  color: #666;
  min-height: 70rpx;
  line-height: 70rpx;
  box-sizing: border-box;
  border: none;
  border-bottom: 1rpx solid #e0e0e0;
  background-color: #fff;
  padding-left: 15rpx;
}

.input[disabled] {
  background-color: #f9f9f9;
  color: #999;
}

.submit-button {
  margin-top: 40rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 10rpx;
}
</style>